
const max = 100; // 输入框最大值
const placeholder = `请输入选项，不超过${max}字符`; // 输入提示
const errorTip = `输入不超过${max}字符`; // 错误提示
const colors1 = [
  'rgb(255, 255, 255)',
  'rgb(214, 229, 255)',
  'rgb(214, 241, 255)',
  'rgb(211, 243, 226)',
  'rgb(255, 220, 219)',
  'rgb(255, 236, 219)',
  'rgb(255, 245, 204)',
  'rgb(251, 219, 255)',
  'rgb(255, 219, 234)'
];
const colors2 = [
  'rgb(220, 223, 228)',
  'rgb(173, 203, 255)',
  'rgb(173, 228, 255)',
  'rgb(172, 226, 197)',
  'rgb(255, 181, 179)',
  'rgb(255, 206, 163)',
  'rgb(255, 234, 153)',
  'rgb(231, 180, 255)',
  'rgb(255, 179, 220)'
];
const colors3 = [
  'rgb(129, 134, 143)',
  'rgb(41, 114, 244)',
  'rgb(0, 163, 245)',
  'rgb(69, 176, 118)',
  'rgb(222, 60, 54)',
  'rgb(248, 136, 37)',
  'rgb(245, 196, 0)',
  'rgb(154, 56, 215)',
  'rgb(221, 64, 151)'
];

const colors = [...colors1, ...colors2, ...colors3];
const defaultResult = [
  { color: colors[0], value: '', id: '0' },
  { color: colors[1], value: '', id: '1' },
  { color: colors[2], value: '', id: '2' }
];
let result = [...defaultResult];
let draging = null; //被拖拽目标
let dragSwitch = false; // 是否可拖拽
let colorVisible = true; // 是否显示颜色
let colorActive = colors[0]; // 当前激活的颜色块
let itemActive = ''; // 当前激活的选项-取的属性id
const colorClass = 'ui-simple-color-td-active'; // 颜色激活class
let outside = false; // 点击在外
const debTime = {
  lasttime1: '',
  timer1: ''
};
//防抖
function debounce(fn, wait, num) {
  const now = +new Date();
  if (debTime['lastTime' + num] - now < wait) {
    clearTimeout(debTime['timer' + num]);
  }
  debTime['timer' + num] = setTimeout(() => {
    fn();
    debTime['lastTime' + num] = +new Date();
  }, wait);
}
// option-初始化
export function initFn(id) {
  const dom = document.getElementById(id);
  const child = document.createElement('div');
  child.id = 'ui-options';
  // list
  const listDom = document.createElement('div');
  listDom.id = 'ui-options-list';
  child.append(listDom);
  dom.append(child);
  // 新增按钮
  const newDom = document.createElement('div');
  newDom.id = 'ui-option-add';
  newDom.innerHTML = `<span class="iconfont icon-zhuce"></span>
  <span>添加一项</span>`;
  newDom.onclick = addItemFn;
  child.append(newDom);
  for (let i = 0; i < defaultResult.length; i++) {
    listDom.append(renderItem(defaultResult[i]));
  }
}
// option-新增一个选项
function addItemFn() {
  const dom = document.getElementById('ui-options-list');
  const len = dom.children.length;
  const param = {
    color: '',
    value: '',
    id: `${len}`
  };
  const lastColor = dom.children[len - 1].getAttribute('item-color');
  for (let i = 0; i < colors.length; i++) {
    if (colors[i] === lastColor) {
      if (i === colors.length - 1) {
        param.color = colors[0];
      } else {
        param.color = colors[i + 1];
      }
    }
  }
  result.push(param);
  dom.append(renderItem(param));
  delChange();
}
// option-render选项
function renderItem(param) {
  const dom = document.createElement('div');
  dom.className = 'ui-options-item';
  dom.draggable = true;
  dom.ondragover = dragOverFn;
  dom.ondragstart = dragStartFn;
  dom.ondragend = getResult;
  // info
  const infoDom = document.createElement('div');
  infoDom.className = 'ui-options-item-info';
  // info-del
  const delDom = document.createElement('span');
  delDom.onclick = delItemFn;
  delDom.className = 'iconfont icon-close-circle ui-options-item-del';
  // info-color
  const colorDom = document.createElement('span');
  colorDom.onclick = openColorFn;
  colorDom.className = 'ui-options-item-color';
  colorDom.style.cssText = `background:${param.color}`;
  if (!colorVisible) {
    colorDom.style.display = 'none';
  }
  // info-输入框
  const input = document.createElement('input');
  input.oninput = inputChange;
  input.onblur = blurFn;
  input.value = param.value;
  input.className = 'ui-options-item-input';
  input.placeholder = placeholder;
  // info-拖拽
  const dragDom = document.createElement('div');
  dragDom.onmouseenter = () => {
    dragSwitch = true;
  };
  dragDom.onmouseleave = () => {
    dragSwitch = false;
  };
  dragDom.className = 'iconfont icon-gengduo ui-options-drag';
  // 错误提示
  const tipDom = document.createElement('div');
  tipDom.className = 'ui-options-item-tip';
  // 设置属性
  dom.setAttribute('item-id', param.id);
  dom.setAttribute('item-color', param.color);
  // 添加dom
  infoDom.append(delDom);
  infoDom.append(colorDom);
  infoDom.append(input);
  infoDom.append(dragDom);
  dom.append(infoDom);
  dom.append(tipDom);
  return dom;
}
// option-数据转换
export function convertList(list = [], visible = true) {
  colorVisible = visible;
  let index = -1;
  result = list.map((item, i) => {
    index++;
    if (index === colors.length - 1) {
      index = 0;
    }
    return {
      color: colors[index],
      value: item,
      id: `${i}`
    };
  });
  // 先清空选项
  const listDom = document.getElementById('ui-options-list');
  listDom.innerHTML = '';
  if (list.length === 0) result = defaultResult;

  for (let i = 0; i < result.length; i++) {
    listDom.append(renderItem(result[i]));
  }
}
// drag-拖拽
function dragStartFn(event) {
  if (!dragSwitch) {
    event.preventDefault();
    return;
  }
  event.dataTransfer.setData('text/html', event.target.innerText); //不能使用text，firefox会打开新tab
  event.dataTransfer.effectAllowed = 'move';
  event.dataTransfer.dropEffect = 'move';
  draging = event.target;
}
// drag-拖拽中
function dragOverFn(event) {
  event.preventDefault();
  event.dataTransfer.effectAllowed = 'move';
  event.dataTransfer.dropEffect = 'move';
  let target = event.target;
  //因为dragover会发生在ul上，所以要判断是不是目标
  if (!target.classList.contains('ui-options-item') || target === draging) return;
  //getBoundingClientRect()用于获取某个元素相对于视窗的位置集合
  let targetRect = target.getBoundingClientRect();
  let dragingRect = draging.getBoundingClientRect();
  if (target && target.animated) return;
  if (findIndex(draging) < findIndex(target)) {
    //nextSibling 属性可返回某个元素之后紧跟的节点（处于同一树层级中）。
    target.parentNode.insertBefore(draging, target.nextSibling);
  } else {
    target.parentNode.insertBefore(draging, target);
  }
  dragAnmiate(dragingRect, draging);
  dragAnmiate(targetRect, target);
}
// drag-拖拽结束设置result值
export function getResult() {
  const domList = document.getElementById('ui-options-list').children;
  result = [];
  for (let i = 0; i < domList.length; i++) {
    const inputDom = getItemInput(domList[i]);
    let param = {
      color: domList[i].getAttribute('item-color'),
      value: inputDom.value,
      id: domList[i].getAttribute('item-id')
    };
    result.push(param);
  }
}
//获取元素在父元素中的index
function findIndex(el) {
  let index = 0;
  if (!el || !el.parentNode) return -1;
  //previousElementSibling属性返回指定元素的前一个兄弟元素（相同节点树层中的前一个元素节点）。
  while (el && (el = el.previousElementSibling)) {
    index++;
  }
  return index;
}
function dragAnmiate(prevRect, target) {
  let ms = 100;
  let currentRect = target.getBoundingClientRect();
  //nodeType 属性返回以数字值返回指定节点的节点类型。1=元素节点  2=属性节点
  if (prevRect.nodeType === 1) {
    prevRect = prevRect.getBoundingClientRect();
  }
  dragCss(target, 'transition', 'none');
  dragCss(target, 'transform', 'translate3d(' + (prevRect.left - currentRect.left) + 'px,' + (prevRect.top - currentRect.top) + 'px,0)');
  // 触发重绘
  target.offsetWidth; // eslint-disable-line
  dragCss(target, 'transition', 'all ' + ms + 'ms');
  dragCss(target, 'transform', 'translate3d(0,0,0)');

  clearTimeout(target.animated);
  target.animated = setTimeout(function () {
    dragCss(target, 'transition', '');
    dragCss(target, 'transform', '');
    target.animated = false;
  }, ms);
}
function dragCss(el, prop, val) {
  let style = el && el.style;
  if (!style) return;
  if (val === 0) {
    //使用DefaultView属性可以指定打开窗体时所用的视图
    if (document.defaultView && document.defaultView.getComputedStyle) {
      val = document.defaultView.getComputedStyle(el, '');
    } else if (el.currentStyle) {
      val = el.currentStyle;
    }
    return prop === 0 ? val : val[prop];
  } else {
    if (!(prop in style)) {
      prop = '-webkit-' + prop;
    }
    style[prop] = val + (typeof val === 'string' ? '' : 'px');
  }
}
// input-输入监听
function inputChange(e) {
  let value = e.target.value;
  value = value.trim(value);
  if (value.length > max) {
    e.target.value = value.substr(0, max);
    errorTipFn(e.target.parentNode.parentNode);
    debounce(clearTipFn.bind(this, e.target.parentNode.parentNode), 5000, 1);
  } else {
    clearTipFn(e.target.parentNode.parentNode);
  }
}
// input-输入框失去焦点
function blurFn(e) {
  const dom = e.target.parentNode.parentNode;
  const tipDom = getTipDom(dom);
  tipDom.innerText = '';
}
// input-添加错误提示
function errorTipFn(target) {
  const tipDom = getTipDom(target);
  tipDom.innerText = errorTip;
}
// input-删除错误提示
function clearTipFn(target) {
  const tipDom = getTipDom(target);
  tipDom.innerText = '';
}
// input-获取当前项的tip
function getTipDom(target) {
  for (let i = 0; i < target.children.length; i++) {
    if (target.children[i].className.includes('ui-options-item-tip')) {
      return target.children[i];
    }
  }
}
// option-删除项
function delItemFn(e) {
  const parentNode = e.target.parentNode.parentNode;
  const id = parentNode.getAttribute('item-id');
  if (result.length === 1) return;
  for (let i = 0; i < result.length; i++) {
    if (id === result[i].id) {
      result.splice(i, 1);
      break;
    }
  }
  parentNode.remove();
  delChange();
}
// 添加/去除删除按钮的禁用
function delChange() {
  const listDom = document.getElementById('ui-options-list');
  if (listDom.children.length === 1) {
    listDom.children[0].classList.add('ui-options-item-disabled');
  } else {
    for (let i = 0; i < listDom.children.length; i++) {
      listDom.children[i].classList.remove('ui-options-item-disabled');
    }
  }
}
// option-取消所有颜色
export function cancelColor() {
  colorVisible = false;
  const domList = document.getElementById('ui-options-list').children;
  for (let i = 0; i < domList.length; i++) {
    const colorDom = getItemColor(domList[i]);
    colorDom.style.display = 'none';
  }
}
// option-初始化选项所有颜色
export function confirmColor() {
  colorVisible = true;
  const domList = document.getElementById('ui-options-list').children;
  let index = 0;
  for (let i = 0; i < domList.length; i++) {
    const colorDom = getItemColor(domList[i]);
    colorDom.style.display = 'block';
    colorDom.style.background = colors[i];
    if (index === colors.length) index = 0;
    domList[i].setAttribute('item-color', colors[index]);
    index++;
  }
}
// option-获取当前激活项
function getActiveDom() {
  const domList = document.getElementById('ui-options-list').children;
  for (let i = 0; i < domList.length; i++) {
    if (domList[i].getAttribute('item-id') === itemActive) {
      return domList[i];
    }
  }
}
// option-获取指定项的color
function getItemColor(itemDom) {
  const domList = itemDom.children[0].children;
  for (let i = 0; i < domList.length; i++) {
    if (domList[i].classList.contains('ui-options-item-color')) {
      return domList[i];
    }
  }
}
// option-获取指定项的input
function getItemInput(itemDom) {
  const domList = itemDom.children[0].children;
  for (let i = 0; i < domList.length; i++) {
    if (domList[i].classList.contains('ui-options-item-input')) {
      return domList[i];
    }
  }
}
// option-设置项的颜色
function setOptionColor(id, color) {
  const domList = document.getElementById('ui-options-list').children;
  for (let i = 0; i < domList.length; i++) {
    const itemId = domList[i].getAttribute('item-id');
    console.log(id, color, domList[i]);

    if (itemId === id) {
      domList[i].setAttribute('item-color', color);
      const spanlist = domList[i].children[0].children;
      for (let j = 0; j < spanlist.length; j++) {
        if (spanlist[j].classList.contains('ui-options-item-color')) {
          spanlist[j].style.background = color;
          break;
        }
      }
      break;
    }
  }
}
// color-初始化
export function initColor() {
  const dom = document.createElement('div');
  dom.id = 'ui-simple-color';
  const domList = renderTd(colors);
  for (let i = 0; i < domList.length; i++) {
    dom.append(domList[i]);
  }

  document.body.append(dom);
  document.getElementById('ui-simple-color').onmouseenter = () => {
    outside = true;
  };
  document.getElementById('ui-simple-color').onmouseleave = () => {
    outside = false;
  };
}
// color-颜色选择
function colorChange(color, e) {
  colorActive = color;
  e.target.classList.add('ui-simple-color-td-active');
  setColorActive();
  setOptionColor(itemActive, colorActive);
  closeColor();
}
// color-render列
function renderTd(arr) {
  return arr.map(item => {
    let dom = document.createElement('span');
    dom.setAttribute('value', item);
    dom.className = 'ui-simple-color-td';
    dom.style.cssText = `background:${item}`;
    dom.onclick = colorChange.bind(this, item);
    return dom;
  });
}
// color-设置颜色选择中项
function setColorActive() {
  const dom = document.getElementById('ui-simple-color').children;
  for (let i = 0; i < dom.length; i++) {
    const color = dom[i].getAttribute('value');
    if (dom[i].classList.contains(colorClass)) dom[i].classList.remove(colorClass);
    if (color === colorActive) dom[i].classList.add(colorClass);
  }
}
// color-关闭
function closeColor() {
  window.removeEventListener('mouseup', onSpaceFn);
  document.getElementById('ui-simple-color').style.display = 'none';
}
// color-打开
function openColorFn(e) {
  window.addEventListener('mouseup', onSpaceFn);
  const dom = e.target.parentNode.parentNode;
  colorActive = dom.getAttribute('item-color');
  itemActive = dom.getAttribute('item-id');
  const itemDom = getActiveDom();
  let { top, left, height } = itemDom.getBoundingClientRect();
  let topNew = top + height;
  const simpleDom = document.getElementById('ui-simple-color');
  if (left + simpleDom.clientWidth > window.innerWidth + 10) {
    left = window.innerWidth - simpleDom.clientWidth - 10;
  }
  if (topNew + simpleDom.clientHeight > window.innerHeight + 10) {
    topNew = top - simpleDom.clientHeight - height;
  }
  simpleDom.style.cssText = `${simpleDom.style.cssText}display:block;
  left:${left}px;top:${topNew}px`;
  setColorActive();
}
// 点击空白判断
function onSpaceFn() {
  if (!outside) closeColor();
  outside = false;
}
